//
//  StatusPictureView.swift
//  weibo
//
//  Created by cmh on 15/9/7.
//  Copyright © 2015年 cmh. All rights reserved.
//

import UIKit
import SDWebImage

private let statusPictureCellID = "statusPictureCellID"

// 选中照片的通知
let XMYStatusPictureViewSelectedPhotoNotification = "XMYStatusPictureViewSelectedPhotoNotification"
// 当前选中的cell 
var XMYStatusPictureViewSelectedPhotoIndexPathKey = "XMYStatusPictureViewSelectedPhotoIndexPathKey"
// 选中照片的URL
let XMYStatusPictureViewSelectedPhotoUrlKey  = "XMYStatusPictureViewSelectedPhotoUrlKey"

class StatusPictureView: UICollectionView {
    
    var statusRowViewModel: StatusRowViewModel? {
        didSet{
           sizeToFit()
            
            // 刷新数据
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return showCollectionSize()
    }
    
    
    // 根据微博中图片的数量，显示图片视图的大小
    private func showCollectionSize() -> CGSize {
    
        let layOut = collectionViewLayout as! UICollectionViewFlowLayout
        
        // 设置默认的视图的大小
        layOut.itemSize = CGSize(width: statusCellPictureWidth, height: statusCellPictureWidth)
        
        // 图片的数量
        let count = statusRowViewModel?.thumbnailURLs?.count ?? 0

        // 1.没有图
        if count == 0  {
            return CGSizeZero
        }
        
        // 2.一张图
        if count == 1 {
            
            var size = CGSize(width: 150, height: 150)
            
            // 取缓存图片
            let key = statusRowViewModel!.thumbnailURLs![0].absoluteString
            
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                
                size = image.size
            }
            
            // 处理过窄或过宽的图片
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > 300 ? 300 : size.width
            
            layOut.itemSize = size
            
            return size
            
        }
        
        // 3. 四张图
        if count == 4 {
            
            let w = 2 * statusCellPictureWidth + statusCellPictureMargin
            
            return CGSize(width: w, height: w)
            
        }
        
        // 其余图片
        // 多少行
        let row = CGFloat((count - 1) / Int(statusCellPictureMaxCount) + 1)
        let h = row * statusCellPictureWidth + (row - 1) * statusCellPictureMargin
        let w = statusCellPictureMaxWidth

        return CGSize(width: w, height: h)
        
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        backgroundColor = UIColor.lightGrayColor()
        
        let layOut = collectionViewLayout as! UICollectionViewFlowLayout
        
        // 设值图片间距
        layOut.minimumInteritemSpacing = statusCellPictureMargin
        layOut.minimumLineSpacing = statusCellPictureMargin
        
        dataSource = self
        delegate = self
        
        // 注册cell标识
        registerClass(statusPictureCell.self, forCellWithReuseIdentifier: statusPictureCellID)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension StatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusRowViewModel?.thumbnailURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureCellID, forIndexPath: indexPath) as! statusPictureCell
        
        cell.imageUrl = statusRowViewModel!.thumbnailURLs![indexPath.item]
        
        return cell
    }
    
    // 选中cell的时候调用
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        
        // 利用通知，传递当前的cell的索引和选中图片的URL
        NSNotificationCenter.defaultCenter().postNotificationName(XMYStatusPictureViewSelectedPhotoNotification, object: self, userInfo: [XMYStatusPictureViewSelectedPhotoIndexPathKey : indexPath, XMYStatusPictureViewSelectedPhotoUrlKey : statusRowViewModel!.bmiddleURLs!])
        
    }
    
    
}

// 实现数据源方法

// 自定义cell
private class statusPictureCell: UICollectionViewCell {
    
    // 图片的url
    var imageUrl: NSURL? {
        didSet {
            showImageView.sd_setImageWithURL(imageUrl)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(showImageView)
        
        showImageView.ff_Fill(self)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 懒加载控件,并设置照片的填充模式
    private var showImageView: UIImageView = {

        let iconView = UIImageView()
        
        // 设置填充样式
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        
        
        return iconView
    }()
    
}
